package ec.edu.udla.fichamedica.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

import ec.edu.udla.fichamedica.client.EntityService;
import ec.edu.udla.fichamedica.client.EntityServiceAsync;
import ec.edu.udla.fichamedica.client.FichaMedicaWebApp;
import ec.edu.udla.fichamedica.client.Home;
import ec.edu.udla.fichamedica.domain.Person;

public class PersonList extends Composite implements HasText {

	private static PersonListUiBinder uiBinder = GWT
			.create(PersonListUiBinder.class);

	interface PersonListUiBinder extends UiBinder<Widget, PersonList> {
	}
	
	List<Person> persons;

	public PersonList() {
//		Window.alert("En el constructor");
		initWidget(uiBinder.createAndBindUi(this));
		
		this.nuevo.setVisible(false);
//		Window.alert("Antes de llamar al servicio personas");
		EntityServiceAsync entityService = GWT.create(EntityService.class);
		entityService.getPersons(GWT.getHostPageBaseURL(),
				new AsyncCallback<List<Person>>() {
					public void onFailure(Throwable error) {
						persons = null;
						System.out.println("Error ..... : "+error.getLocalizedMessage());
						Window.alert("Error ..... : "+error.getLocalizedMessage());
						
					}

					@Override
					public void onSuccess(List<Person> result) {
						persons = result;
						
						TextColumn<Person> codigoColumn = new TextColumn<Person>() {
							@Override
							public String getValue(Person person) {
								return person.getCodigo();
							}
						};

						// Make the name column sortable.
						codigoColumn.setSortable(true);
						
						
						TextColumn<Person> pinColumn = new TextColumn<Person>() {
							@Override
							public String getValue(Person person) {
								return person.getPin();
							}
						};

						// Make the name column sortable.
						pinColumn.setSortable(true);
						
						TextColumn<Person> surnameColumn = new TextColumn<Person>() {
							@Override
							public String getValue(Person person) {
								return person.getSurname();
							}
						};

						// Make the name column sortable.
						surnameColumn.setSortable(true);

						TextColumn<Person> nameColumn = new TextColumn<Person>() {
							@Override
							public String getValue(Person person) {
								return person.getName();
							}
						};
						// Make the name column sortable.
						nameColumn.setSortable(true);
						
						TextColumn<Person> documentTypeColumn = new TextColumn<Person>() {
							@Override
							public String getValue(Person person) {
								return person.getDocumentType()!=null?person.getDocumentType().name():"";
							}
						};
						// Make the name column sortable.
						documentTypeColumn.setSortable(true);


						// Add the columns.
						cellTable.addColumn(codigoColumn, "Codigo");
						cellTable.addColumn(documentTypeColumn, "Tipo de Documento");
						cellTable.addColumn(pinColumn, "Numero de Documento");
						cellTable.addColumn(nameColumn, "Nombres");
						cellTable.addColumn(surnameColumn, "Apellidos");
						

						if (persons != null && persons.size() > 0)
						{
							cellTable.setRowData(persons);
							// Add a selection model to handle user selection.
						    final SingleSelectionModel<Person> selectionModel = new SingleSelectionModel<Person>();
						    selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
						        public void onSelectionChange(SelectionChangeEvent event) {
						          Person selected = selectionModel.getSelectedObject();
						          if (selected != null) {
						        	  Home home = new Home();

						      		FichaMedicaWebApp.driver.initialize(home);
						      		FichaMedicaWebApp.driver.edit(selected);

						      		RootPanel.get().clear();
						      		RootPanel.get().add(home);
						          }
						        }
						      });
						    
						    cellTable.setSelectionModel(selectionModel);
							
//							Window.alert("Se encontraron "+persons.size()+" registros");
						}
						
						 nuevo.setVisible(true);
						
					}
				});
		
		
	}

	@UiField(provided = true)
	CellTable<Person> cellTable = new CellTable<Person>();
	@UiField
	Button nuevo;

	public PersonList(List<Person> persons) {
		initWidget(uiBinder.createAndBindUi(this));
	}

	public void setText(String text) {

	}

	public String getText() {
		return "";
	}

	@UiHandler("nuevo")
	void onNuevoClick(ClickEvent event) {

		Home home = new Home();

		FichaMedicaWebApp.driver.initialize(home);
		FichaMedicaWebApp.driver.edit(new Person());

		RootPanel.get().clear();
		RootPanel.get().add(home);
	}

}
